package com.m3958.firstgwt.client.window;

import java.util.HashMap;
import java.util.Map;

import com.google.inject.Singleton;
import com.m3958.firstgwt.client.rpc.MyTextCallback;
import com.smartgwt.client.rpc.RPCManager;
import com.smartgwt.client.rpc.RPCRequest;
import com.smartgwt.client.types.Alignment;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.IButton;
import com.smartgwt.client.widgets.Window;
import com.smartgwt.client.widgets.events.ClickEvent;
import com.smartgwt.client.widgets.events.ClickHandler;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.fields.TextItem;
import com.smartgwt.client.widgets.layout.HLayout;
import com.smartgwt.client.widgets.layout.VLayout;

@Singleton
public class FakeToUserWindow extends Window{


	private boolean initialized = false;
	
	public FakeToUserWindow(){
		setWidth(350);
		setHeight(200);
		setIsModal(true);
		setShowModalMask(true);
		setTitle("切换到其他用户");
		centerInPage();
	}
	
	public FakeToUserWindow showMe(){
		if(!initialized){
			initialized = true;
			VLayout layout = new VLayout(5);
			DynamicForm df = new DynamicForm();
			final TextItem ti = new TextItem("用户名");
			df.setItems(ti);
			layout.addMember(df);
			IButton b = new IButton("切换");
			b.addClickHandler(new ClickHandler() {
				@Override
				public void onClick(ClickEvent event) {
					if(ti.getValueAsString() == null || ti.getValueAsString().isEmpty())return;
					Map<String, String> m = new HashMap<String, String>();
			    	m.put("username", ti.getValueAsString());
			    	m.put("dowhat", "fake2user");
			    	RPCRequest rr = new RPCRequest();
			    	rr.setHttpMethod("GET");
			    	rr.setActionURL("/notrpclogin");
			    	rr.setParams(m);
			    	RPCManager.sendRequest(rr,new MyTextCallback(){
						@Override
						public void afterSuccess(String result) {
							if("true".equals(result)){
								com.google.gwt.user.client.Window.Location.reload();
							}else{
								SC.warn("切换失败！");
							}
						}});
				}
			});
			layout.addMember(b);
			layout.addMember(initBt());
			addItem(layout);
		}
		show();
		return this;
	}
	

	private HLayout initBt() {
		HLayout hl = new HLayout();
		hl.setHeight(25);
		hl.setAlign(Alignment.RIGHT);
		IButton ib = new IButton("关闭");
		ib.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				FakeToUserWindow.this.hide();
			}
		});
		hl.addMember(ib);
		return hl;
	}
}
